<?php

/**
 * @Author: CraspHB彬
 * @Date:   2018-06-26 15:46:49
 * @Email:   646054215@qq.com
 * @Last Modified time: 2018-07-13 10:45:23
 */
namespace app\install\controller;
use think\Controller;
use think\Request;
class Index extends Controller{
	/**
	 * 判断是否安装过
	 * @return [type] [description]
	 */
    public function _initialize(){
    	//已经安装过了,跳过安装
    	if(file_exists('./data/install.lock')){
    		
             $this->redirect(url('admin/login/index'));
    	}
    }
	public function index(){
		session('step', 1);
		return $this->fetch('/index');
	}

	public function step2(){
		$step = session('step');
		session('step' , 2);
		if ($step != 1 && $step != 2  && $step != 3  && $step != 4) {
			$this->error('请按照顺序安装');
		}
		$data = [];
		$data['phpversion'] = phpversion();
		$data['php_os'] = PHP_OS;
 		$icon_correct='<i class="fa fa-check correct"></i> ';
        $icon_error='<i class="fa fa-close error"></i> ';		
		if (class_exists('pdo')) {
            $data['pdo'] = $icon_correct.'已开启';
        } else {
            $data['pdo'] = $icon_error.'未开启';
        }
        //扩展检测
        if (extension_loaded('pdo_mysql')) {
            $data['pdo_mysql'] = $icon_correct.'已开启';
        } else {
            $data['pdo_mysql'] =$icon_error.'未开启';
        }
        if (extension_loaded('mbstring')) {
            $data['mbstring'] = $icon_correct.'已开启';
        } else {
            $data['mbstring'] = $icon_error.'未开启';
        }
        //设置获取
        if (ini_get('file_uploads')) {
            $data['upload_size'] = $icon_correct . ini_get('upload_max_filesize');
        } else {
            $data['upload_size'] = $icon_error.'禁止上传';
        }
        if (ini_get('allow_url_fopen')) {
            $data['allow_url_fopen'] = $icon_correct.'已开启';
        } else {
            $data['allow_url_fopen'] = $icon_error.'未开启';
        }
        //函数检测
        if (function_exists('file_get_contents')) {
            $data['file_get_contents'] = $icon_correct.'已开启';
        } else {
            $data['file_get_contents'] = $icon_error.'未开启';
        }
        if (function_exists('session_start')) {
            $data['session'] = $icon_correct.'已开启';
        } else {
            $data['session'] = $icon_error.'未开启';
        }
        //检测文件夹属性
        $checklist = [
            'application/database.php',
            'data',
            'data/config/config.php',
            'data/runtime',
            'upload',
        ];
        $new_checklist = [];
        foreach($checklist as $dir){
            if(!is_file($dir)){
                $testdir = "./".$dir;

                //不存在创建文件并赋予权限
                if(!is_dir($testdir)){
                	mkdir($testdir,0777,true);
                }
                if(is_writable($testdir)){
                    $new_checklist[$dir]['w']=true;
                }else{
                    $new_checklist[$dir]['w']=false;
                }
                if(is_readable($testdir)){
                    $new_checklist[$dir]['r']=true;
                }else{
                    $new_checklist[$dir]['r']=false;
                }
            }else{
                if(is_writable($dir)){
                    $new_checklist[$dir]['w']=true;
                }else{
                    $new_checklist[$dir]['w']=false;
                }
                if(is_readable($dir)){
                    $new_checklist[$dir]['r']=true;
                }else{
                    $new_checklist[$dir]['r']=false;
                }
            }
        }	
        $data['checklist'] = $new_checklist;	
		$this->assign('data',$data);
		return $this->fetch('/step2');
	}
	public function step3(){
		$step = session('step');
		session('step' , 3);
		if ($step != 1 && $step != 2 && $step != 3  && $step != 4 ) {
			$this->error('请按照顺序安装');
		}
		return $this->fetch('/step3');
	}
	public function step4(){
		$step = session('step');
		session('step' , 4);
		if($step != 3 && $step != 4){
			$this->error('请按照顺序安装');
		}	
        $data = input('post.');
		$dsn = "mysql:host=".$data['dbhost'].";port=".$data['dbport'].";charset=UTF8;";
        try {
            $pdo = new \PDO($dsn , $data['dbuser'] , $data['dbpw']);
        } catch (\PDOException $e) {
        	 $this->error('数据库连接失败', url('install/Index/step3'));
        }
        //创建数据库
        $pdo->exec("DROP DATABASE IF EXISTS ".$data['dbname']);
        if(!($pdo->exec("CREATE DATABASE IF NOT EXISTS `{$data['dbname']}` DEFAULT CHARACTER SET utf8"))) $this->error('创建数据库失败', url('install/Index/step3'));

        //重新连接数据库
        $dsn = "mysql:dbname=".$data['dbname'].";host=".$data['dbhost'].";port=".$data['dbport'].";charset=UTF8;";
        try{
            $pdodb = new \PDO($dsn , $data['dbuser'] , $data['dbpw']);
        }catch( \ PDOException $e){
              $this->error('数据库连接失败', url('install/Index/step3'));
        }
        echo $this->fetch('/step4');
        $prefix = $data['dbprefix'];
        //导入数据表
        $sql = file_get_contents('./data/hbbcms.sql');
        $exec = sql_split($sql,$prefix);
        //导入sql
        foreach($exec as $item){
            //创建表并返回信息CREATE TABLE `cms_auth_group`
            if(preg_match('/CREATE TABLE `([^ ]*)`/',$item,$arr)){
                $msg = "创建数据表".$arr[1];
                echo  $this->showMsg($msg , "success");
                if(($pdodb->exec($item)) !== false){
                    $msg = "创建数据表{$arr[1]}成功";
                    $res = "success";
                }else{
                    $msg = "创建数据表{$arr[1]}失败";
                    $res = "error";
                    session('error',true);
                }
                echo  $this->showMsg($msg , $res);
            }else{
                $pdodb->exec($item);
            }
        }
        //管理员表插入数据
        $pwd_mix = get_mix();
        $email = $data['email'];
        $password = get_password($pwd_mix,$data['password']);        
        if(($pdodb->exec("INSERT INTO {$prefix}admin (`id` , `username` , `password` ,`pwd_mix` , `email` , `status` , `addtime`) VALUES ( 1 ,'".$data['username']."','".$password."','".$pwd_mix."','".$email."','1','".time()."' )")) == false){
            session('error',true);
        }
        //数据库database.php更新
        $database = file_get_contents('./data/database.php');
        $database = str_replace(['@hostport','@database','@username','@password','@hostname','@prefix'], [$data['dbport'],$data['dbname'],$data['dbuser'],$data['dbpw'],$data['dbhost'],$data['dbprefix']] , $database);        
        file_put_contents('./application/database.php',$database);
        //修改配置
        set_config('prefix',$prefix);//数据库前缀
        $web_sys = get_config('web_sys');
        $web_sys['site_name'] = $data['site_name'];
        $web_sys['site_url'] = $data['site_url'] ;
        set_config('web_sys',$web_sys);
        file_put_contents('./data/install.lock','');
        if(session('error')){
            $this->error("安装失败",url('install/index/step3'));
        }else{
            $this->success("即将安装完成",url('install/index/step5'));
        }
	}
    public function step5(){
        $step = session('step');
        if($step != 4){
            $this->error('请按照顺序安装');
        }           
        return $this->fetch('/step5');
    }
    public function showMsg($msg , $res){
        $return = <<<EOT
        <script type="text/javascript">
           showmsg("{$msg}","{$res}")
        </script>
EOT;
     return $return;
    }
	public function testdb(){
		if(Request::instance()->isPost()){
			$data = input('post.');
			//$DB = new PDO('mysql:host=127.0.0.1;port=3306;dbname=anexis_new;charset=UTF8;','root','password', array(PDO::ATTR_PERSISTENT=>true));
			$dsn = "mysql:host=".$data['hostname'].";port=".$data['hostport'].";charset=UTF8;";
            try {
                $pdo = new \PDO($dsn ,trim( $data['username']) ,trim($data['password']));
            } catch (\PDOException $e) {
            	$this->error($e->getMessage());
            }
   //          //判断数据库是否存在
   //          $sql = "SELECT information_schema.SCHEMATA.SCHEMA_NAME FROM information_schema.SCHEMATA where SCHEMA_NAME='".$data['dbname']."';";
   //          $res = [];
   //          foreach($pdo->query($sql) as $val){  
			//     $res = $val;  
			// }  
			// if(!empty($res)){
			// 	$this->error('数据库已存在,是否覆盖');
			// }
            $this->success('配置成功');
		}
		$this->error('提交方式不正确!');
	}
}
